// 全局配置AJAX ERROR
$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    // console.log('ajax错误');
});

// 解决JQuery发送Ajax请求后，IE缓存数据不更新的问题
$.ajaxSetup({
    global: true,
    cache: false,
    error: function(jqXHR, textStatus, errorMsg){
        var response =jqXHR.responseText;
        // alert(jqXHR.status);
        switch (jqXHR.status){

            case(401):
//                alert("您还未登录！");
//                var refURL = window.location.href;
//                window.location.href = "../../../user/login/page/login.html?ref="+refURL;
                break;
            case(500):
                // alert(response.message);
                //window.location.href = "../../common/page/500.html";
                break;
            case(403):
                //alert("无权限执行此操作");
                window.location.href = "../../common/page/403.html";
                break;
            case(404):
                //alert("页面未找到");
                //window.location.href = "../../common/page/404.html";
                break;
            case(408):
                //alert("请求超时");
                window.location.href = "../../common/page/408.html";
                break;
            default:
                //alert("未知错误");
                //window.location.href = "../../common/page/unknow.html";
        }
    }
});

// 表单提交阻止默认动作并清除焦点
$('form').submit(function(e) {
    e.preventDefault();
    $(this).find('input').blur();
});

//复选框 全选 ------------------------------------
(function() {
	// 判断浏览器是否支持 placeholder 
	if(!placeholderSupport()){   
	 
	    $('[placeholder]').focus(function() { 

	        var input = $(this); 

	        if (input.val() == input.attr('placeholder')) { 



	        } 

	    }).blur(function() { 

	        var input = $(this); 
	        var value = input.attr('placeholder');
	        if (input.val() == '' || input.val() == input.attr('placeholder')) { 
	        	if(value != null && value!= undefined)
	        		$(input).parent().append("<i style=''>"+value+"</i>")
	        	  input.val(''); 
		            input.removeAttr('placeholder'); 
		            

	        } 

	    }).blur();
	       
	};	

    $('body').on('click', '.chkall', function(e) {
        e.stopPropagation();
        var chkall = $(this);
        var chklist = chkall.parents('table').find('.invechk');
        var flag = chkall.prop('checked');

        chklist.each(function(i, o) {
            if ($(o).attr('disabled')!="disabled") {
                $(o).prop('checked', flag);
            };
        });
    });

    $('body').on('click', '.invechk', function(e) {
        e.stopPropagation();
        var flag = true;
        var table = $(this).parents('table');
        var chkall = table.find('.chkall');
        var chklist = table.find('.invechk');

        chklist.each(function(i, o) {
            if ($(o).prop('checked') == false) {
                flag = false;
            }
        });
        chkall.prop('checked', flag);
    });
    
})();
function placeholderSupport() { 

    return 'placeholder' in document.createElement('input'); 

}

/*** 提示框 ***/
$.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, {
    _title: function(title) {
        if (!this.options.title) {
            title.html("&#160;");
        } else {
            title.html(this.options.title);
        }
    }
}));

$('#dialog_del').dialog({
    autoOpen: false,
    width: 400,
    resizable: false,
    modal: true,
    title: "<div class='widget-header'><h4><i class='text-danger fa fa-warning'></i> 提示</h4></div>",
    position: {
        my: "center",
        at: "top+30%",
        of: window
    }
});

$('#dialog_assess').dialog({
    autoOpen: false,
    width: 400,
    resizable: false,
    modal: true,
    title: "<div class='widget-header'><h4><i class='text-danger fa fa-warning'></i> 提示</h4></div>",
    position: {
        my: "center",
        at: "top+30%",
        of: window
    }
});


//提示对话框

function showMsgPane(s, type, callback) {
    var btns = '';
    var type = type || 'prompt';

    $('#modal-msg').remove();

    if (type == 'prompt') {
        btns = ' <button class="btn" onclick="hideMsgPane()">确定</button> '
    } else if (type == 'confirm') {
        btns = ' <button class="btn" onclick="hideMsgPane()">取消</button> ' + ' <button class="btn btn-primary" id="btn-msg-ok">确定</button> ';
    }else if (type == 'alert') {
        btns = ' <button class="btn" id="btn-msg-ok">确定</button> '
    };

    var html = '<div id="modal-msg" class="modal hide" tabindex="-1" role="dialog" aria-labelledby="lbl-modal-msg" aria-hidden="true" data-backdrop="false"> ' + '  <div class="modal-header"> ' + '    <button type="button" class="close" onclick="hideMsgPane()">×</button> ' + '    <h3 id="lbl-modal-msg">提示</h3> ' + '  </div> ' + '  <div class="modal-body"> ' + '    <p>' + s + '</p> ' + '  </div> ' + '  <div class="modal-footer"> ' + btns + '  </div> ' + '</div>';

    $('body').append(html);

    var fn = null;
    if (typeof callback == 'function') {
        fn = function() {
            //hideMsgPane();
            $('#modal-msg').hide(function() {
                $('body').off('click', '#btn-msg-ok');
                $('#modal-msg').remove();
                callback();
            });


        };
    } else {
        fn = function() {
            hideMsgPane();
        };
    }

    $('body').on('click', '#btn-msg-ok', fn);
    // $('#modal-msg').modal('show');
    $('#modal-msg').show();

}

function hideMsgPane() {
    // $('#modal-msg').modal('hide');
    // $('#modal-msg').on('hidden', function () {
    //     $('body').off('click', '#btn-msg-ok');
    //     $('#modal-msg').remove();
    // });
    $('#modal-msg').hide(function() {
        $('body').off('click', '#btn-msg-ok');
        $('#modal-msg').remove();
    });
}
 

/* Chinese initialisation for the jQuery UI date picker plugin. */
/* Written by Cloudream (cloudream@gmail.com). */
jQuery(function($){
$.datepicker.regional['zh-CN'] = {
closeText: '关闭',
prevText: '上月',
nextText: '下月',
currentText: '今天',
monthNames: ['一月','二月','三月','四月','五月','六月',
'七月','八月','九月','十月','十一月','十二月'],
monthNamesShort: ['一','二','三','四','五','六',
'七','八','九','十','十一','十二'],
dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
dayNamesMin: ['日','一','二','三','四','五','六'],
weekHeader: '周',
dateFormat: 'yy-mm-dd',
changeYear:true,
changeMonth:true,
firstDay: 1,
isRTL: false,
showMonthAfterYear: true,
yearSuffix: '&nbsp;年&nbsp;',
monthSuffix: '&nbsp;月&nbsp;'};
$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
});


//清空表单
function clearForm(form) {
    var formObj = document.getElementById(form);
    if (formObj == undefined) {
        return;
    }

    for ( var i = 0; i < formObj.elements.length; i++) {
        if (formObj.elements[i].type == "text") {
            formObj.elements[i].value = "";
         }
         //deleted by ygao from clear form but hidden element
          else if (formObj.elements[i].type == "hidden") {
             formObj.elements[i].value = "";
        } else if (formObj.elements[i].type == "password" ) {
            formObj.elements[i].value = "";
        } else if (formObj.elements[i].type == "radio") {
            formObj.elements[i].checked = "";
        } else if (formObj.elements[i].type == "checkbox" ) {
            formObj.elements[i].checked = false;
        } else if (formObj.elements[i].type == "select-one" ) {
            formObj.elements[i].options[0].selected = true ;
        } else if (formObj.elements[i].type == "select-multiple" ) {
            for ( var j = 0; j < formObj.elements[i].options.length; j++) {
                formObj.elements[i].options[j].selected = false ;
            }
        } else if (formObj.elements[i].type == "file") {
            //formObj.elements[i].select();
            //document.selection.clear();            
            // for IE, Opera, Safari , Chrome
            var file = formObj.elements[i];
            if (file.outerHTML) {
                file.outerHTML = file.outerHTML;
            } else {
                file.value = ""; // FF(包括3.5)
            }
        } else if (formObj.elements[i].type == "textarea" ) {
            formObj.elements[i].value = "";
        }
    }

}

//显示蒙层提示
function showDialog(msg) {
    jQuery("<div/>").attr("id", "dialog").appendTo("body");
    jQuery('#dialog').dialog({
        autoOpen: false,
        width: 400,
        // dialogClass: "noclose",
        modal: true,
        title: "<div class='widget-header'><h4><i class='text-danger fa fa-warning'></i> 提示</h4></div>",
        buttons: { "确定": function() { 
            jQuery(this).dialog("close"); 
            jQuery('.noclose').remove();
            jQuery('#dialog').remove(); } },
        resizable: false
    });
    jQuery("#dialog").html(msg);
    jQuery("#dialog").dialog("open");
}

function trimStr(str){
	return str.replace(/(^\s*)|(\s*$)/g,'');
}

Date.prototype.Format = function (fmt) { 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var customerId = "0FA1C730-9552-46A7-A632-7784224414CE";
var roleId = "01";

// IE浏览器判断
// var _IE = (function(){ 
//     if (!!window.ActiveXObject || "ActiveXObject" in window)  
//         return true;  
//     else  
//         return false;  
// }()); 

// IE下jarviswidget-toggle-btn点击报错
// if (_IE) {
    // jarviswidget 放大缩小按钮事件
//     $('.jarviswidget').on('click', '.jarviswidget-toggle-btn', function () {
//         var anchor = $(this).parents('.jarviswidget');
//         var btn = $(this).find('.fa');
//         if (btn.hasClass('fa-minus')) {
//             $('#widget-content', anchor).hide();
//         }
//         if (btn.hasClass('fa-plus')) {
//             $('#widget-content', anchor).show();
//         }
//     });
// }

//获取URL中参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}
//验证文件扩展名,
//参数：
//fileName 文件名
//arr_exts 允许扩展名的数组
function IsValidFileExtention(fileName,arr_exts)
{
    var arrayExt = fileName.split(".");
    var fileExt = arrayExt[arrayExt.length - 1].toLowerCase();
    var isValid = false;
    for(var i = 0;i < arr_exts.length;i++)
    {
        if(isValid = arr_exts[i] == fileExt)
        {
            break;
        }
    }
    return isValid;
}
//判断上传文件大小
//fileId 文件Id
//maxsize 文件大小
function IsValidFileSize( fileId,maxsize) 
{     
    var tipMsg = "您的浏览器暂不支持计算上传文件的大小，建议使用IE、FireFox、Chrome浏览器。";
    var browserCfg = {};
    var ua = window.navigator.userAgent;
    if (ua.indexOf("MSIE")>=1 || ua.indexOf('Trident') >= 1) {
      browserCfg.ie = true;
    } else if(ua.indexOf("Firefox")>=1){
      browserCfg.firefox = true;
    }else if(ua.indexOf("Chrome")>=1){
     browserCfg.chrome = true;
    }  
    try{
     var obj_file =document.getElementById(fileId);
     if (obj_file.value == "") {
      alert("请先选择上传文件");
      return;
     }
     var filesize = 0;
     if ( browserCfg.firefox || browserCfg.chrome ) {
      filesize = obj_file.files[0].size;
     } else if (browserCfg.ie) {
      filesize = obj_file.files[0].size;       
     } else {
       alert(tipMsg);
       return;
     }
     if (filesize==-1) {
      alert(tipMsg);
      return;
     } else if(filesize > maxsize) {      
      return false;
    } else{
      return true;
    }
   } catch(e) {
    alert(e);
   }  
}
  
// 表格排序，表头点击事件
function sort_handle(tbodyId, a) {
    var a = $(a);
    var field = a.data('field');

    if (a.find('.fa-arrow-down').length > 0) {
        a.find('.fa-arrow-down').removeClass('fa-arrow-down').addClass('fa-arrow-up');
        // 升序处理函数
        sortTable(tbodyId, field, 'asc');
    } else if (a.find('.fa-arrow-up').length > 0) {
        a.find('.fa-arrow-up').removeClass('fa-arrow-up').addClass('fa-arrow-down');
        // 降序处理函数
        sortTable(tbodyId, field, 'desc');
    } else {
        a.parents('thead').find('i.fa').remove();
        a.append('<i class="fa fa-arrow-down"></i>');
        // 降序处理函数
        sortTable(tbodyId, field, 'desc');
    }

}

function sortreport(th) {
    var th = $(th);
    th.siblings().removeClass('headerSortDown');
    th.siblings().removeClass('headerSortUp');
    var field = th.data('field');
    if (th.hasClass('headerSortDown')) {
        th.removeClass('headerSortDown').addClass('headerSortUp');
        sortReportTable(field, 'asc');
    } else if (th.hasClass('headerSortUp')) {
        th.removeClass('headerSortUp').addClass('headerSortDown');
        sortReportTable(field, 'desc');
    } else {
        th.addClass('headerSortUp');
        sortReportTable(field, 'asc');
    }
}

// 为datepicker 自定义afterShow事件
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function (inst) {
    $.datepicker._updateDatepicker_original(inst);
    var afterShow = this._get(inst, 'afterShow');
    if (afterShow)
        afterShow.apply((inst.input ? inst.input[0] : null));
}

/**
 * 点击上传，搜索用户
 */
function upload_member_search_excel(){
	 var strFileName = $('#member-search-file').val();
	    if (strFileName.length > 0) {
	        if (!IsValidFileExtention(strFileName, ["xls"])) {
	            alert("文件格式不正确！");
	            return false;
	        } else {
	            var formData = new FormData();
	            formData.append("file", document.getElementById('member-search-file').files[0]);
	            var url_proxy = $.cookie('resource_proxy').replace(/\"/g, "");
	            $.ajax({
	                    url: url_proxy,
	                    type: 'POST',
	                    data: formData,
	                    cache: false,
	                    contentType: false,
	                    processData: false,
	                    success: function(returndata) {
	                        var json = returndata;
	                        var fileurl = json.data[0].fileId; // 获取文件路径
	                        var url ="/server/member/info/getbatch/search.json";
	                        $.ajax({
	                                type: "post",
	                                url: url,
	                                dataType: "json",
	                                data: {
	                                    filePath: fileurl
	                                },
	                                async: false,
	                                success: function(rtn) {
	                                	$('#import-search-batch-id').val(rtn.message);
	                                	load_import_search_member_list(0);
	                                }
	                          });
	                    }
	                });
	        }
	    }
}

function load_import_search_member_list(pageno){
	var url = "/server/import/discovery/pagelist.json";
	var data = $('#member-search-form').serialize();
	$.post(url, data, function(rtn){
		var datalist = load_import_search_member_list_html(rtn);
	})
}

function  load_import_search_member_list_html(page){
	var tpl = [
		'{@each content as it, k}',
		'{@/each}',
	].join("\n");
	return juicer(tpl, page);
}